package com.david.reader.activity

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.text.TextUtils
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import android.widget.FrameLayout
import android.widget.TextView
import android.widget.Toast
import com.david.core.utils.DpUtils
import com.david.core.utils.PreferenceUtils
import com.david.reader.bean.BookBean
import com.david.reader.utils.BookHelper
import com.david.reader.R
//import com.david.reader.txt.TxtDataBase
import com.david.reader.utils.FileUtil
import com.david.reader.view.JustifyTextView
import com.github.barteksc.pdfviewer.PDFView
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener
import kotlinx.coroutines.*
import java.io.*


/**
 * TODO 区分章节；存储章节中每页开始结束索引数据进行获取数据；
 * TODO 添加从文件管理app直接接收文件打开功能，并提示是否添加到书架
 *
 * TODO 添加最近阅读历史
 *
 * TODO txt小说使用数据库（room）存储每页数据
 * */
class ReaderActivity:Activity(), OnPageChangeListener {
    private lateinit var panel_center: JustifyTextView
    //var dataBase:TxtDataBase? = null


    private var currentPage:Int = 0
    private var bookName = ""
    private var pageTextSize = 0
    private var lineCount = 0
    private var lineTextSize = 0
    private var skippedCharsSize = 0L

    private var name = "在苦难的日子里"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

//        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

        setContentView(R.layout.activity_reader)

        if (!TextUtils.isEmpty(intent.getStringExtra("name"))) {
            if (intent.getIntExtra("type", 1) == 0) {
//                intent.getStringExtra("simpleName")?.let { readTxt(it) }
            } else {
                intent.getStringExtra("uri")?.let { loadBook(it) }
            }
        } else {
            intent?.apply {
                data?.let {

                    loadBook(data!!)

                    addButton(data.toString().substring(data.toString().lastIndexOf("/") + 1), data!!)
                }
            }
        }



//        panel_center = findViewById(R.id.text_panel_1)
//        val assetManager = this.assets
//        val fontFace = Typeface.createFromAsset(assetManager, "fonts/Roboto-Regular.ttf")
//        panel_center.setTypeface(fontFace)
//        currentPage = PreferenceUtils.getInstance()?.getInt(bookName+"current_page", 0)!!
//        pageTextSize = PreferenceUtils.getInstance()?.getInt("page_text_size") ?: 0
//        lineCount = PreferenceUtils.getInstance()?.getInt("line_count") ?: 0
//        lineTextSize = PreferenceUtils.getInstance()?.getInt("line_text_size") ?: 0
//        skippedCharsSize = PreferenceUtils.getInstance()?.getLong("skiped_chars_size") ?: 0
//
//        val window: Window = window
//        window.statusBarColor = getColor(R.color.color_light_green)
//
//        if (pageTextSize > 0) {
//            getPageTexts()
//        }

//        findViewById<TextView>(R.id.text_panel_1).setText("在家里时，四舍八邻都不富裕，因此谁也不为" +
//                "在家里时，是不是，因此谁也不:为" +
//                "在家里时，四舍八邻都不《富裕，因此'谁也不为" +
//                "在家里时，四舍八邻都不富裕，因此谁也》不为" +
//                "在家里时，四舍八。邻都不富裕，因此谁,也不为" +
//                "在家里时，四舍八邻都不富裕，因此谁.也不为。" +
//                "在家里时，四舍八邻都不富裕，因此谁{也不为。" +
//                "在家里时，四舍八邻都不富裕，因此谁]也不为。"
//        )
    }

    private fun loadBook(data:Uri){
        name = data.toString().substring(data.toString().lastIndexOf("/") + 1)
        val view = findViewById<PDFView>(R.id.pdf_view)
        view.visibility = View.VISIBLE
            view.fromUri(data)
            .onPageChange(this@ReaderActivity)
            .defaultPage(PreferenceUtils.getInstance().getInt(name + "_page", 0))
            .spacing(5)
            .fitEachPage(false)
            .load()
    }

    private fun loadBook(path:String){
        name = path.substring(path.lastIndexOf("/") + 1)
        val view = findViewById<PDFView>(R.id.pdf_view)
        view.visibility = View.VISIBLE
        view.fromFile(File(path))
            .onPageChange(this@ReaderActivity)
            .defaultPage(PreferenceUtils.getInstance().getInt(name + "_page", 0))
            .spacing(5)
            .fitEachPage(false)
            .load()
    }

//    private fun readTxt(txtName:String){
//        panel_center = findViewById(R.id.text_panel_1)
//        panel_center.text = ""
//        panel_center.visibility = View.VISIBLE
//
//        CoroutineScope(Dispatchers.IO).launch {
//            dataBase =
//                TxtDataBase.getTxtDataBase(this@ReaderActivity, txtName)
//            currentPage = 1
//            val str = dataBase?.txtPageDao()?.getContentByPage(
//                currentPage
//            )
//            withContext(Dispatchers.Main) {
//                panel_center.text = str?.content ?: "If you don't sit still, you must be tied down,' said Bessie. 'Miss Abbot, lend me your garters; she would break mine directly.'\\n\n" +
//                        "  Miss Abbot turned to divest a stout leg of the necessary ligature. This preparation for bonds, and the additional ignominy it inferred, took a little of the excitement out of me.\\n\n" +
//                        "  'Don't take them off,' I cried; 'I will not stir.'\n" +
//                        "  In guarantee whereof, I attached myself to my seat by my hands.\n"
//            }
//        }
//
//        panel_center.setOnClickListener {
//            CoroutineScope(Dispatchers.IO).launch {
//                val str = dataBase?.txtPageDao()?.getContentByPage(
//                    ++currentPage
//                )
//                withContext(Dispatchers.Main) {
//                    panel_center.text = str?.content ?: "If you don't sit still, you must be tied down,' said Bessie. 'Miss Abbot, lend me your garters; she would break mine directly.'\\n\n" +
//                            "  Miss Abbot turned to divest a stout leg of the necessary ligature. This preparation for bonds, and the additional ignominy it inferred, took a little of the excitement out of me.\\n\n" +
//                            "  'Don't take them off,' I cried; 'I will not stir.'\n" +
//                            "  In guarantee whereof, I attached myself to my seat by my hands.\n"
//                }
//            }
//        }
//    }


    override fun onResume() {
        super.onResume()
//        if (pageTextSize == 0) {
//            panel_center.postDelayed(object :Runnable{
//                override fun run() {
////                panel_center.setText("" + (panel_center.width/panel_center.textSize))
//                    panel_center.setText(
//                        "买上一辆豪华轿车" +
//                                "   里时，四舍八邻都不富裕，因此谁也不为" +
//                                "在家里时，四舍八邻都不富裕，因此谁也不为" +
//                                "在家里时，四舍八邻都不富裕，因此谁也不为" +
//                                "在家里时，四舍八邻都不富裕，因此谁也不为" +
//                                "在家里时，四舍八邻都不富裕，因此谁也不为" +
//                                "在家里时，四舍八邻都不富裕，因此谁也不为" +
//                                "在家里时，四舍八邻都不富裕，因此谁也不为" +
//                                "在家里时，四舍八邻都不富裕，因此谁也不为" +
//                                "在家里时，四舍八邻都不富裕，因此谁也不为" +
//                                "在家里时，四舍八邻都不富裕，因此谁也不为" +
//                                "在家里时，四舍八邻都不富裕，因此谁也不为" +
//                                "在家里时，四舍八邻都不富裕，因此谁也不为" +
//                                "在家里时，四舍八邻都不富裕，因此谁也不为" +
//                                "在家里时，四舍八邻都不富裕，因此谁也不为" +
//                                "在家里时，四舍八邻都不富裕，因此谁也不为" +
//                                "在家里时，四舍八邻都不富裕，因此谁也不为" +
//                                "在家里时，四舍八邻都不富裕，因此谁也不为" +
//                                "在家里时，四舍八邻都不富裕，因此谁也不为" +
//                                "在家里时，四舍八邻都不富裕，因此谁也不为" +
//                                "在家里时，四舍八邻都不富裕，因此谁也不为" +
//                                "在家里时，四舍八邻都不富裕，因此谁也不为" +
//                                "在家里时，四舍八邻都不富裕，因此谁也不为" +
//                                "在家里时，四舍八邻都不富裕，因此谁也不为" +
//                                "在家里时，四舍八邻都不富裕，因此谁也不为" +
//                                (panel_center.width/panel_center.textSize) +
//                                " "+ (panel_center.height/(panel_center.lineSpacingExtra + panel_center.lineHeight)))
//
//                    pageTextSize  = (panel_center.width/panel_center.textSize).toInt() * ((panel_center.height/(panel_center.lineSpacingExtra + panel_center.lineHeight)).toInt())
//                    lineCount = (panel_center.height/(panel_center.lineSpacingExtra + panel_center.lineHeight)).toInt()
//                    lineTextSize = (panel_center.width/panel_center.textSize).toInt()
//                    PreferenceUtils.getInstance()?.setInt("page_text_size", pageTextSize)
//                    PreferenceUtils.getInstance()?.setInt("line_count", lineCount)
//                    PreferenceUtils.getInstance()?.setInt("line_text_size", lineTextSize)
//
//                    getPageTexts()
//
//                    panel_center.width = (lineTextSize * panel_center.textSize).toInt()
//
//                    Log.e("info", ""+ pageTextSize + " " + lineCount +" "+lineTextSize)
//
//                }
//            }, 1000)
//        }
    }

    private var lines:ArrayList<String> = java.util.ArrayList()
    private var pages:ArrayList<String> = ArrayList()

    private var content = ""
    private var readedIndex = 0

    private fun getPageTexts(){

        var dir = File(Environment.getExternalStorageDirectory().absolutePath + "/cache/" + name)
        if (!dir.exists()) {//还没分页保存
            dir.mkdirs()

            if (panel_center.getOnPageShowFinishListener() == null) {
                panel_center.setOnPageShowFinishListener(object :
                    JustifyTextView.OnPageShowFinishListener {
                    override fun onPageShowed(lastIndex: Int) {
                        readedIndex += lastIndex + 1
                    }

                })
            }

            try {
                val reader = BufferedReader(
                    FileReader(Environment.getExternalStorageDirectory().absolutePath + "/DingTalk/在困难的日子里_6.txt"),
                    20
                )

                if (skippedCharsSize > 0)
                    reader.skip(skippedCharsSize)
                var lineContent: String = reader.readLine()

                content = lineContent + "\n"

                var savePage = 0

                while ((lineContent) != null) {
                    if (lines.size >= lineCount * 20) {
                        break
                    }
                    if (lineContent.length <= lineTextSize) {
                        lines.add(lineContent + "\n");
                    } else {
                        if (lineContent != null) {
                            while (lineContent.length > lineTextSize) {
                                val tempStr = lineContent.substring(0, lineTextSize)
                                lines.add(tempStr)
                                lineContent = lineContent.substring(lineTextSize)
                            }
                            lines.add(lineContent + "\n")
                        }
                    }


                    val tempContent: String? = reader.readLine()


                    // TODO: 2021/7/3 按章节保存每页数据
                    if (lines.size >= lineCount || tempContent == null) {
                        var page = ""
                        val tempLines = ArrayList<String>()
                        for (index in 0 until lines.size) {
                            if (index < lineCount) {
                                page += lines.get(index)
                            } else {
                                tempLines.add(lines.get(index))
                            }
                        }
                        if (savePage == 0) {
                            panel_center.text = page
                        }
                        val file = File(dir.absolutePath + "/" + savePage + ".txt")
                        val writer = FileWriter(file)
                        writer.write(page)
                        writer.flush()
                        writer.close()
                        lines.clear()
                        lines.addAll(tempLines)
                        ++savePage
                    }
                    if (tempContent == null) {
                        break
                    }
                    lineContent = tempContent
                    Log.e("content", lineContent)

                    if (!TextUtils.isEmpty(lineContent))
                        content += lineContent + "\n"
                }

//            var pageText: String
//            for (index in 0 until 10) {
//                pageText = ""
//                for (innerIndex in 0 until lineCount) {
//                    pageText += lines[innerIndex + index*lineCount]
//                }
//                pages.add(pageText)
//            }
//
////            panel_center.text = content.substring(readedIndex)+"\n"
//            panel_center.text = pages[0]
//            Log.e("page" , pages[0])

            } catch (e: FileNotFoundException) {
                e.printStackTrace()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        } else {//已经分页保存了
            panel_center.text =
            getPageFromFile(dir, currentPage)
        }
    }

    private fun getPageFromFile(dir:File,page:Int):String{
        val reader = FileReader(dir.absolutePath + "/"+page+".txt")
        val lines = reader.readLines()
        var tempPage = ""
        for (index in lines.indices) {
            tempPage += lines[index] + "\n"
        }
        return tempPage
    }

    /**
     * 缓存pdf文件阅读到哪一页了
     * */
    override fun onPageChanged(page: Int, pageCount: Int) {
        PreferenceUtils.getInstance().setInt(name + "_page", page)
    }

//    override fun onTouchEvent(event: MotionEvent?): Boolean {
//        if (event != null) {
//            if (event.action == ACTION_UP) {
//                if (event.x < 200) {
//                    if (currentPage > 0) {
//                        panel_center.text = getPageFromFile(File(Environment.getExternalStorageDirectory().absolutePath + "/cache/" + name), --currentPage)
////                        panel_center.text = pages[--currentPage]
////                        panel_center.text = pages[0]
////                        Log.e("page" , pages[currentPage])
//
//                    }
//                } else if (event.x > panel_center.width - 200) {
////                    panel_center.text = content.substring(readedIndex+1)
//                    ++currentPage
////                    panel_center.text = pages[currentPage]
//                    panel_center.text = getPageFromFile(File(Environment.getExternalStorageDirectory().absolutePath + "/cache/" + name), currentPage)
//
////                    Log.e("page" , pages[currentPage])
//
//                }
//            }
//        }
//        return super.onTouchEvent(event)
//    }

    /**
     * 添加加入书架按钮
     */
    private fun addButton(name: String, fileUri: Uri) {
        val text = TextView(this)
        text.text = "加入书架"

        findViewById<FrameLayout>(R.id.reader_root).addView(text)
        (text.layoutParams as FrameLayout.LayoutParams).apply {

            gravity = Gravity.END
            rightMargin = DpUtils.dp2Px(applicationContext, 20)
            marginEnd = DpUtils.dp2Px(applicationContext, 20)
            topMargin = DpUtils.dp2Px(applicationContext, 20f)

            width = FrameLayout.LayoutParams.WRAP_CONTENT
            height = FrameLayout.LayoutParams.WRAP_CONTENT
        }

        text.background = getDrawable(R.drawable.selector_btn_add_shell)

        text.setPadding(DpUtils.dp2Px(applicationContext, 15), DpUtils.dp2Px(applicationContext, 5), DpUtils.dp2Px(applicationContext, 15), DpUtils.dp2Px(applicationContext, 5))



        val fileName = fileUri.toString().substring(fileUri.toString().lastIndexOf("/") + 1)
        val filePath = getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS)?.absolutePath + "/" + fileName
        if (!BookHelper.instance.isBookListInit()) {
            CoroutineScope(Dispatchers.IO).launch{
                BookHelper.instance.loadList()
                val hasItem = BookHelper.instance.hasItem(fileName, 1)
                withContext(Dispatchers.Main){
                    setBtnListener(text, fileUri, hasItem)
                }
            }
        } else {
            val hasItem = BookHelper.instance.hasItem(fileName, 1)
            setBtnListener(text, fileUri, hasItem)
        }
    }

    private fun setBtnListener(btn:TextView, fileUri:Uri, hasItem:Boolean){
        if (!hasItem) {
            btn.setOnClickListener {//目前先使用preference，后期可改为mmkv
                PreferenceUtils.getInstance().setString(name, fileUri.toString())

                FileUtil.copyFileToCache(applicationContext, fileUri)

                BookHelper.instance.addItem(0, BookBean(name, 1))

                Toast.makeText(this, "添加成功", Toast.LENGTH_LONG).show()

                setNavBack(btn)
            }
        } else {
            setNavBack(btn)
        }
    }

    private fun setNavBack(btn: TextView){
        btn.text = "返回列表"
        btn.setOnClickListener {
            startActivity(Intent(this, BookShellActivity::class.java))
            finish()
        }
    }
}